package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class PurchaseServlet
 */
@WebServlet(urlPatterns = { "/Purchase", "/purchase", "/PurchaseServlet", "/purchaseServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class PurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public PurchaseServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<PurchaseModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("purchaseNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			PurchaseModel query = new PurchaseModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());

			PurchaseModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("purchase", obj);
				getServletContext().getRequestDispatcher("/purchaseEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			PurchaseModel query = new PurchaseModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());

			PurchaseModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("purchase", obj);
				getServletContext().getRequestDispatcher("/purchaseView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			PurchaseModel obj = new PurchaseModel();

			// SET NAME here

			GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());
			int res = 0;

			try {
				String strName = request.getParameter("name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("purchase", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			PurchaseModel query = new PurchaseModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("purchaseList.jsp");
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {
			
			PurchaseModel obj = new PurchaseModel();
			String name = request.getParameter("name");
					obj.setName(name);

String code = request.getParameter("code");
					obj.setCode(code);

String description = request.getParameter("description");
					obj.setDescription(description);



//String plan_cost = request.getParameter("plan_cost");
//                    if (plan_cost != null && !plan_cost.isEmpty()) {
//					    obj.setPlanCost(Double.parseDouble(plan_cost));
//                    }
//
//String real_cost = request.getParameter("real_cost");
//                    if (real_cost != null && !real_cost.isEmpty()) {
//					    obj.setRealCost(Double.parseDouble(real_cost));
//                    }
//
//
//String plan_order_time_date = request.getParameter("plan_order_time_date");
//    String plan_order_time_time = request.getParameter("plan_order_time_time");
//    if (plan_order_time_date != null && !plan_order_time_date.isEmpty() && plan_order_time_time != null && !plan_order_time_time.isEmpty()) {
//            obj.setPlanOrderTime(DateTimeUtil.parseDateTime(plan_order_time_date, plan_order_time_time));
//} else {
//    obj.setPlanOrderTime(DateTimeUtil.parseDate(plan_order_time_date));
//}


String plan_delivery_time_date = request.getParameter("plan_delivery_time_date");
    String plan_delivery_time_time = request.getParameter("plan_delivery_time_time");
    if (plan_delivery_time_date != null && !plan_delivery_time_date.isEmpty() && plan_delivery_time_time != null && !plan_delivery_time_time.isEmpty()) {
            obj.setPlanDeliveryTime(DateTimeUtil.parseDateTime(plan_delivery_time_date, plan_delivery_time_time));
} else {
    obj.setPlanDeliveryTime(DateTimeUtil.parseDate(plan_delivery_time_date));
}


//String real_order_tate_date = request.getParameter("real_order_tate_date");
//    String real_order_tate_time = request.getParameter("real_order_tate_time");
//    if (real_order_tate_date != null && !real_order_tate_date.isEmpty() && real_order_tate_time != null && !real_order_tate_time.isEmpty()) {
//            obj.setRealOrderTate(DateTimeUtil.parseDateTime(real_order_tate_date, real_order_tate_time));
//} else {
//    obj.setRealOrderTate(DateTimeUtil.parseDate(real_order_tate_date));
//}


String real_delivery_time_date = request.getParameter("real_delivery_time_date");
    String real_delivery_time_time = request.getParameter("real_delivery_time_time");
    if (real_delivery_time_date != null && !real_delivery_time_date.isEmpty() && real_delivery_time_time != null && !real_delivery_time_time.isEmpty()) {
            obj.setRealDeliveryTime(DateTimeUtil.parseDateTime(real_delivery_time_date, real_delivery_time_time));
} else {
    obj.setRealDeliveryTime(DateTimeUtil.parseDate(real_delivery_time_date));
}

//String need_approval = request.getParameter("need_approval");
//					obj.setNeedApproval(need_approval.equalsIgnoreCase("true")
//							|| need_approval.equalsIgnoreCase("1"));

String status = request.getParameter("status");
                    if (status != null && !status.isEmpty()) {
					    obj.setStatus(Integer.parseInt(status));
                    }

//String is_draft = request.getParameter("is_draft");
//					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//							|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }



String remark = request.getParameter("remark");
					obj.setRemark(remark);

String purchaser = request.getParameter("purchaser");
                    if (purchaser != null && !purchaser.isEmpty()) {
					    obj.setPurchaser(Integer.parseInt(purchaser));
                    }

String supplier = request.getParameter("supplier");
                    if (supplier != null && !supplier.isEmpty()) {
					    obj.setSupplier(Integer.parseInt(supplier));
                    }

String id_currency = request.getParameter("id_currency");
                    if (id_currency != null && !id_currency.isEmpty()) {
					    obj.setIdCurrency(Integer.parseInt(id_currency));
                    }

String id_project = request.getParameter("id_project");
                    if (id_project != null && !id_project.isEmpty()) {
					    obj.setIdProject(Integer.parseInt(id_project));
                    }

String discount = request.getParameter("discount");
                    if (discount != null && !discount.isEmpty()) {
					    obj.setDiscount(Double.parseDouble(discount));
                    }

String additional_cost = request.getParameter("additional_cost");
                    if (additional_cost != null && !additional_cost.isEmpty()) {
					    obj.setAdditionalCost(Double.parseDouble(additional_cost));
                    }


String order_time_date = request.getParameter("order_time_date");
    String order_time_time = request.getParameter("order_time_time");
    if (order_time_date != null && !order_time_date.isEmpty() && order_time_time != null && !order_time_time.isEmpty()) {
            obj.setOrderTime(DateTimeUtil.parseDateTime(order_time_date, order_time_time));
} else {
    obj.setOrderTime(DateTimeUtil.parseDate(order_time_date));
}

String id_quotation = request.getParameter("id_quotation");
                    if (id_quotation != null && !id_quotation.isEmpty()) {
					    obj.setIdQuotation(Integer.parseInt(id_quotation));
                    }

String id_quotation_item = request.getParameter("id_quotation_item");
                    if (id_quotation_item != null && !id_quotation_item.isEmpty()) {
					    obj.setIdQuotationItem(Integer.parseInt(id_quotation_item));
                    }
                    
                    String id_checklist = request.getParameter("id_checklist");
                    if (id_checklist != null && !id_checklist.isEmpty()) {
					    obj.setIdChecklist(Integer.parseInt(id_checklist));
                    }
                    
                    String id_task = request.getParameter("id_task");
                    if (id_task != null && !id_task.isEmpty()) {
					    obj.setIdTask(Integer.parseInt(id_task));
                    }
                    
                    String id_event = request.getParameter("id_event");
                    if (id_event != null && !id_event.isEmpty()) {
					    obj.setIdEvent(Integer.parseInt(id_event));
                    }


String payment_date_date = request.getParameter("payment_date_date");
    String payment_date_time = request.getParameter("payment_date_time");
    if (payment_date_date != null && !payment_date_date.isEmpty() && payment_date_time != null && !payment_date_time.isEmpty()) {
            obj.setPaymentDate(DateTimeUtil.parseDateTime(payment_date_date, payment_date_time));
} else {
    obj.setPaymentDate(DateTimeUtil.parseDate(payment_date_date));
}

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, refresh cache and redirect to somewhere
					response.sendRedirect("purchaseNew.jsp");
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("purchase", obj);
				getServletContext().getRequestDispatcher("/purchaseInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			PurchaseModel query = new PurchaseModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());

			PurchaseModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				
				String name = request.getParameter("name");
					obj.setName(name);

String code = request.getParameter("code");
					obj.setCode(code);

String description = request.getParameter("description");
					obj.setDescription(description);


//String plan_cost = request.getParameter("plan_cost");
//                    if (plan_cost != null && !plan_cost.isEmpty()) {
//					    obj.setPlanCost(Double.parseDouble(plan_cost));
//                    }
//
//String real_cost = request.getParameter("real_cost");
//                    if (real_cost != null && !real_cost.isEmpty()) {
//					    obj.setRealCost(Double.parseDouble(real_cost));
//                    }
//
//
//String plan_order_time_date = request.getParameter("plan_order_time_date");
//    String plan_order_time_time = request.getParameter("plan_order_time_time");
//    if (plan_order_time_date != null && !plan_order_time_date.isEmpty() && plan_order_time_time != null && !plan_order_time_time.isEmpty()) {
//            obj.setPlanOrderTime(DateTimeUtil.parseDateTime(plan_order_time_date, plan_order_time_time));
//} else {
//    obj.setPlanOrderTime(DateTimeUtil.parseDate(plan_order_time_date));
//}


String plan_delivery_time_date = request.getParameter("plan_delivery_time_date");
    String plan_delivery_time_time = request.getParameter("plan_delivery_time_time");
    if (plan_delivery_time_date != null && !plan_delivery_time_date.isEmpty() && plan_delivery_time_time != null && !plan_delivery_time_time.isEmpty()) {
            obj.setPlanDeliveryTime(DateTimeUtil.parseDateTime(plan_delivery_time_date, plan_delivery_time_time));
} else {
    obj.setPlanDeliveryTime(DateTimeUtil.parseDate(plan_delivery_time_date));
}


//String real_order_tate_date = request.getParameter("real_order_tate_date");
//    String real_order_tate_time = request.getParameter("real_order_tate_time");
//    if (real_order_tate_date != null && !real_order_tate_date.isEmpty() && real_order_tate_time != null && !real_order_tate_time.isEmpty()) {
//            obj.setRealOrderTate(DateTimeUtil.parseDateTime(real_order_tate_date, real_order_tate_time));
//} else {
//    obj.setRealOrderTate(DateTimeUtil.parseDate(real_order_tate_date));
//}


String real_delivery_time_date = request.getParameter("real_delivery_time_date");
    String real_delivery_time_time = request.getParameter("real_delivery_time_time");
    if (real_delivery_time_date != null && !real_delivery_time_date.isEmpty() && real_delivery_time_time != null && !real_delivery_time_time.isEmpty()) {
            obj.setRealDeliveryTime(DateTimeUtil.parseDateTime(real_delivery_time_date, real_delivery_time_time));
} else {
    obj.setRealDeliveryTime(DateTimeUtil.parseDate(real_delivery_time_date));
}

//String need_approval = request.getParameter("need_approval");
//					obj.setNeedApproval(need_approval.equalsIgnoreCase("true")
//							|| need_approval.equalsIgnoreCase("1"));

String status = request.getParameter("status");
                    if (status != null && !status.isEmpty()) {
					    obj.setStatus(Integer.parseInt(status));
                    }

//String is_draft = request.getParameter("is_draft");
//					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//							|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }



String remark = request.getParameter("remark");
					obj.setRemark(remark);

String purchaser = request.getParameter("purchaser");
                    if (purchaser != null && !purchaser.isEmpty()) {
					    obj.setPurchaser(Integer.parseInt(purchaser));
                    }

String supplier = request.getParameter("supplier");
                    if (supplier != null && !supplier.isEmpty()) {
					    obj.setSupplier(Integer.parseInt(supplier));
                    }

String id_currency = request.getParameter("id_currency");
                    if (id_currency != null && !id_currency.isEmpty()) {
					    obj.setIdCurrency(Integer.parseInt(id_currency));
                    }

String id_project = request.getParameter("id_project");
                    if (id_project != null && !id_project.isEmpty()) {
					    obj.setIdProject(Integer.parseInt(id_project));
                    }

String discount = request.getParameter("discount");
                    if (discount != null && !discount.isEmpty()) {
					    obj.setDiscount(Double.parseDouble(discount));
                    }

String additional_cost = request.getParameter("additional_cost");
                    if (additional_cost != null && !additional_cost.isEmpty()) {
					    obj.setAdditionalCost(Double.parseDouble(additional_cost));
                    }


String order_time_date = request.getParameter("order_time_date");
    String order_time_time = request.getParameter("order_time_time");
    if (order_time_date != null && !order_time_date.isEmpty() && order_time_time != null && !order_time_time.isEmpty()) {
            obj.setOrderTime(DateTimeUtil.parseDateTime(order_time_date, order_time_time));
} else {
    obj.setOrderTime(DateTimeUtil.parseDate(order_time_date));
}

String id_quotation = request.getParameter("id_quotation");
                    if (id_quotation != null && !id_quotation.isEmpty()) {
					    obj.setIdQuotation(Integer.parseInt(id_quotation));
                    }
                    else
                    {
                    	obj.setIdQuotation(Integer.MIN_VALUE);
                    }
                    	

String id_quotation_item = request.getParameter("id_quotation_item");
                    if (id_quotation_item != null && !id_quotation_item.isEmpty()) {
					    obj.setIdQuotationItem(Integer.parseInt(id_quotation_item));
                    }
                    else
                    {
                    	obj.setIdQuotationItem(Integer.MIN_VALUE);
                    }
                    
                    String id_checklist = request.getParameter("id_checklist");
                    if (id_checklist != null && !id_checklist.isEmpty()) {
					    obj.setIdChecklist(Integer.parseInt(id_checklist));
                    }
                    else
                    {
                    	obj.setIdChecklist(Integer.MIN_VALUE);
                    }
                    
                    String id_task = request.getParameter("id_task");
                    if (id_task != null && !id_task.isEmpty()) {
					    obj.setIdTask(Integer.parseInt(id_task));
                    }
                    else
                    {
                    	obj.setIdTask(Integer.MIN_VALUE);
                    }
                    
                    String id_event = request.getParameter("id_event");
                    if (id_event != null && !id_event.isEmpty()) {
					    obj.setIdEvent(Integer.parseInt(id_event));
                    }
                    else
                    {
                    	obj.setIdEvent(Integer.MIN_VALUE);
                    }


String payment_date_date = request.getParameter("payment_date_date");
    String payment_date_time = request.getParameter("payment_date_time");
    if (payment_date_date != null && !payment_date_date.isEmpty() && payment_date_time != null && !payment_date_time.isEmpty()) {
            obj.setPaymentDate(DateTimeUtil.parseDateTime(payment_date_date, payment_date_time));
} else {
    obj.setPaymentDate(DateTimeUtil.parseDate(payment_date_date));
}

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("purchaseList.jsp");
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("purchase", obj);
					getServletContext().getRequestDispatcher("/purchaseList.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			PurchaseModel obj = new PurchaseModel();

			// SET NAME here

			GenericDal<PurchaseModel, PurchaseModelExt> dal = new GenericDal<PurchaseModel, PurchaseModelExt>(new PurchaseModel());
			int res = 0;

			try {
				String strName = request.getParameter("name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("purchase", "" + res);
					out.println(resultXML);
				}
				else
				{
					//TODO: respone something
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}